package com.cskaoyan.www.fe;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;


public class WebServer {

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8080);
            while (true){
                Socket socket = serverSocket.accept();

                InputStream inputStream = socket.getInputStream();
                String url = getRequestURL(inputStream);

                OutputStream outputStream = socket.getOutputStream();
                response(outputStream, url);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getRequestURL( InputStream inputStream ) throws IOException {

        byte[] bytes = new byte[2048];
        StringBuffer stringBuffer = new StringBuffer();
        int read = inputStream.read(bytes);
        for (int i = 0; i < read; i++) {
            stringBuffer.append((char) bytes[i]);
        }
        String content = stringBuffer.toString();

       // System.out.println(content);

        if(content != null && !"".equals(content)){
            int a = content.indexOf(' ');
            int b = content.indexOf(' ',a + 1);
            String fileName = content.substring(a + 2, b);

            int i = fileName.indexOf('?');
            if(i != -1){
                return fileName.substring(0,i);
            }
            return fileName;
        }
        return null;
    }


    public static void response(OutputStream outputStream, String url) throws IOException {
        if(url != null){
            if (url.endsWith("ico")){
                return;
            }
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("HTTP/1.1 200 ok \r\n");
            stringBuffer.append("Content-Type:text/html;charset=utf-8 \r\n");
            stringBuffer.append("Access-Control-Allow-Origin:* \r\n");
            stringBuffer.append("\r\n");


            if (url.equals("1")){
                stringBuffer.append("xxx");
            }else if (url.equals("2")){
                stringBuffer.append("ls");
            }else {

                stringBuffer.append("<img src='https://gjusp.alicdn.com/img/img_1653986231739_49.png@1000y-0+ic_60Q.png'>");
            }

            System.out.println(stringBuffer);

            outputStream.write(stringBuffer.toString().getBytes("utf-8"));
            outputStream.close();
        }
    }

}
